'''
Created on 28/09/2009

@author: b1u3fox
'''
from gtk import TextView, gdk, STATE_NORMAL, TEXT_WINDOW_WIDGET
from gtk import Menu, MenuItem, Window, WINDOW_POPUP, Notebook
from gtk import VBox, TreeView, TreeViewColumn, CellRendererText, ListStore
from gobject import TYPE_STRING
import pango

from interprete.analex import Analex, Token
from settings import SETTINGS

class Autocompletador(Window):
    pass

class ResaltadorSintaxis(TextView):
    
    clases_tokens = {}
    clases_tokens['palabras_reservadas'] = [Token.ABS, Token.ADJ, 
        Token.ASOC, Token.ATAUT, Token.CONM, Token.CONTR, Token.DCOND, 
        Token.DIMPL, Token.DEM, Token.IMPL, Token.DIST, Token.DISTCUANT,
        Token.DBLNEG, Token.EE, Token.EU, Token.GE, Token.GU, Token.IDENT,
        Token.IDEMP, Token.INTCUANT, Token.LDM, Token.LSA, Token.MP, 
        Token.MT, Token.MTP, Token.PDEM, Token.RAA, Token.RP, Token.SD, 
        Token.SD, Token.SH, Token.SIMPL, Token.TAUT]
    clases_tokens['corchetes'] = [Token.CABRE, Token.CCIERRA]
    clases_tokens['cuantificadores'] = [Token.EXISTE, Token.PARATODO]
    clases_tokens['conectivos'] = [Token.NO, Token.O, Token.SI, Token.SII,
                                   Token.Y]
    clases_tokens['parentesis'] = [Token.PABRE, Token.PCIERRA]
    clases_tokens['identificadores_min'] = [Token.IDMIN]
    clases_tokens['identificadores_may'] = [Token.IDMAY]
    clases_tokens['numeros'] = [Token.NUMERO]
    clases_tokens['puntos'] = [Token.PUNTO]
    clases_tokens['comas'] = [Token.COMA]
    clases_tokens['dos_puntos'] = [Token.DOSPTOS]
    clases_tokens['igual'] = [Token.IGUAL]
    clases_tokens['cadena_simple'] = [Token.CADENASPL]
    clases_tokens['cadena_doble'] = [Token.CADENADBL]
    clases_tokens['errores'] = [Token.ERROR]
#        FDA = 'FDA'
    token_clase = {}
    for k,v in clases_tokens.iteritems():
        for token in v:
            token_clase[token] = k
    
    def __init__(self):
        TextView.__init__(self)
        self.connect('key-release-event', self.resaltar_sintaxis)
        self.connect('key-release-event', self.resaltar_sintaxis)
        self.connect('key-press-event', self.mover_cursor_guindow)
        #self.connect('key-press-event', self.autocompletar)
        self.get_buffer().connect('insert-text', self.autocompletar)
        self.inicializar_tags()
        self.analex = Analex('')
        self.anterior_cadena = ''
        
        font_str = SETTINGS['editor']['fuente']
        font_str += ' ' + SETTINGS['editor']['estilo']
        font_str += ' ' + SETTINGS['editor']['peso']
        font_str += ' ' + SETTINGS['editor']['tamano']

        font_desc = pango.FontDescription(font_str)
        self.modify_font(font_desc)
        self.modify_base(STATE_NORMAL, 
                         gdk.color_parse(SETTINGS['editor']['fondo']))
        self.guindow = None
        
    def inicializar_tags(self):
        text_buffer = self.get_buffer()
        for k,v in SETTINGS['colores'].iteritems():
            if k == 'errores':
                text_buffer.create_tag(k, underline=pango.UNDERLINE_ERROR)
            else:
                text_buffer.create_tag(k, foreground=v)
                
    def mover_cursor_guindow(self, widget=None, evento=None):
        if evento.keyval == 65362:
            self.celda -= 1
            self.guindow_vista.set_cursor_on_cell(self.celda)
            return True
        elif evento.keyval == 65364:
            self.celda += 1
            self.guindow_vista.set_cursor_on_cell(self.celda)
            return True
        else:
            return False
                    
    def autocompletar(self, textbuffer, iter, text, length):
        if not self.guindow:
            self.guindow = Window(WINDOW_POPUP)
            vbox = VBox()
            modelo = ListStore(TYPE_STRING)
            vista = TreeView(modelo)
            vista.set_headers_visible(False)
            renderer = CellRendererText()
            col = TreeViewColumn(None, renderer, text=0)
            vista.append_column(col)
            modelo.append(['Hola viteh'])
            modelo.append(['Tengo chaleco'])
            modelo.append(['Yo quiero un sanguche!'])
            vbox.pack_start(vista)
            self.guindow.add(vbox)
            vista.set_cursor_on_cell(0)
            self.celda = 0
            self.guindow_vista = vista
        self.guindow.move(*self.situar(iter))
        self.guindow.show_all()
#        menu.popup(None, None, self.situar, 1, 0, iter)
#        menu.get_parent().set_modal(False)
#        self.grab_focus()
        
    def situar(self, iter):
        buf_loc = self.get_iter_location(iter)
        win_x, win_y = self.buffer_to_window_coords(TEXT_WINDOW_WIDGET, 
                                                    buf_loc.x,
                                                    buf_loc.y)
        window = self.get_window(TEXT_WINDOW_WIDGET)
        x, y = window.get_origin()
        return win_x + x + buf_loc.width, win_y + y + buf_loc.height
        
    def resaltar_sintaxis(self, widget=None, evento=None):
        text_buffer = self.get_buffer()
        buff_start, buff_end = text_buffer.get_bounds()
        cadena = text_buffer.get_text(buff_start, buff_end)
        if cadena and cadena != self.anterior_cadena:
            text_buffer.remove_all_tags(buff_start, buff_end)
            tokens = []
            self.analex.multilinea.cadena = unicode(cadena)
            self.analex.reiniciar()
            token = self.analex.preanalisis()
            while token.tipo != Token.FDA:
                start = text_buffer.get_iter_at_offset(token.inicio)
                end = text_buffer.get_iter_at_offset(token.fin)
                tag = self.token_clase[token.tipo]
                text_buffer.apply_tag_by_name(tag, start, end)
                self.analex.avanzar()
                token = self.analex.preanalisis()
        self.anterior_cadena = cadena
        
class Editor(TextView):
    pass
        
class Multieditor(Notebook):
    pass